package com.life.ai.server.framework.satoken;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaStrategy;
import com.life.ai.server.common.domain.R;
import com.life.ai.server.common.exception.errorcode.BaseErrorCode;
import com.life.ai.server.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * SessionInterceptor
 *
 * @author kylewka
 * @since 2023/7/12
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    public boolean isAnnotation = true;

    public TokenInterceptor() {
    }

    @Override
    @SuppressWarnings("all")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (this.isAnnotation && handler instanceof HandlerMethod) {
            // 获取方法注解
            Method method = ((HandlerMethod) handler).getMethod();
            if ((Boolean) SaStrategy.me.isAnnotationPresent.apply(method, SaIgnore.class)) {
                // 当前接口存在免登注解
                return true;
            }
            try {
                // 登录验证
                StpUtil.checkLogin();
                // 链式校验方法注解（权限验证等）
                SaStrategy.me.checkMethodAnnotation.accept(method);
            }catch (SaTokenException e) {
                String requestURI = request.getRequestURI();
                log.warn("请求地址'{}',{}", requestURI, e.getMessage());
                if (e instanceof NotLoginException) {
                    ServletUtils.renderString(response, R.fail(BaseErrorCode.USER_AUTH_EXPIRED).toJson());
                } else if (e instanceof NotPermissionException || e instanceof NotRoleException) {
                    ServletUtils.renderString(response, R.fail(BaseErrorCode.USER_PERMIT_ERROR).toJson());
                } else {
                    ServletUtils.renderString(response, R.fail(BaseErrorCode.USER_LOGIN_ERROR).toJson());
                }
                return false;
            }
        }
        return true;
    }
}
